<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="product" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="70" align="center">
      </el-table-column>
      <el-table-column type="index" width="70" align="center">
      </el-table-column>
      <el-table-column prop="name" label="服务名称" width="150" sortable align="center">
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="100" sortable align="center">
      </el-table-column>
      <el-table-column prop="saleprice" label="卖价" width="100" sortable align="center">
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="140" sortable align="center">
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="140" sortable align="center">
      </el-table-column>

      <el-table-column prop="resources" label="服务参考" width="170" align="center">
        <template scope="scope">
          <img :src="imgPrefix+scope.row.resources.split(',')[0]" width="70px">
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable align="center">

        <template scope="scope">
          <span style="color: #13ce66" v-if="scope.row.state==1">上架</span>
          <span style="color: red" v-else>下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="100" align="center">
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页栏数据-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :total="totals" style="float:right;" :current-page="currentPage">
      </el-pagination>
    </el-col>


    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input placeholder="请输入服务名称" v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入金额" v-model="saveForm.costprice" auto-complete="off" maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="卖价" prop="saleprice">
          <el-input oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入金额" v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="resources" label="服务参考">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            &nbsp;&nbsp;
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="出售数量" prop="saleprice">
          <el-input oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入出售数量" v-model="saveForm.salecount" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <!-- v-if="saveForm.productDetail"-->
          <quill-editor v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail"  :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="服务明细" prop="orderNotice">
          <quill-editor v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
      imgPrefix: "http://123.207.27.208",
      product: [],
      totals: 0,
      currentPage: 1,
      pageSize: 5,
      keyword: "",
      title: "",
      listLoading: false,
      sels: [],//列表选中列
      //文件上传相关数据
      fileList: [],


      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,

      //表单匹配验证,name和sn必须输入值才能继续操作
      saveFormRules: {
        name: [
          {required: true, message: '请输入服务名称', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入成本价', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入卖价', trigger: 'blur'}
        ],
        salecount: [
          {required: true, message: '请输入数量', trigger: 'blur'}
        ]
      },

      //编辑界面数据,都给默认值,重置数据方便添加方法,数值类型默认null,字符串默认空串
      saveForm: {
        id: null,
        name: '',
        costprice: null,
        saleprice: null,
        resources: '',
        salecount:null,
        state: null,
        offsaletime: '',
        onsaletime: '',
        createtime: '',
        productDetail: {  //与后端实体类一致
          intro: '',
          orderNotice: '',
        },
      }
    }
  },


  methods: {
    spilit(){
      let strings = this.product.resources.split(",");
      this.product.resources = strings[0];
    },
    //文件上传的业务逻辑
    handleSuccess: function (response, file, fileList) {
      if (this.saveForm.resources) {
        this.saveForm.resources = this.saveForm.resources + "," + response.obj;
      } else {
        this.saveForm.resources = response.obj;
      }

      this.fileList = [];
      if (this.saveForm.resources) {
        let arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }

    },
    //文件删除的业务逻辑
    handleRemove: function (file, fileList) {
      //1.调用删除接口删除图片
      //Object { url:"http://123.207.27.208/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg"}
      //console.log(file);
      //http://localhost:8080/fastDfs?path=/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      var path = file.url.substring(file.url.indexOf("/group")); //  /group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功")
        }else{
          this.$message.error("删除失败")
        }
      })

      //2.对resource做处理
      // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg,/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i];
          if(path==item){//找到了删除的图片
            arr.splice(i,1);//删除指定的图片
          }
        }
        this.saveForm.resources = arr.join(",")
      }


      //3.对fileList的处理 - 前端显示图片的
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; //group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },
    getProduct() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/product", para).then(res => {
        this.totals = res.data.totals;
        this.product = res.data.data;
        //显示完毕将加载圈消失
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("网络繁忙,请稍后再试..")
      })
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.getProduct();
    },

    //3.高级查询
    keywordQuery() {
      this.currentPage = 1;
      this.getProduct();
    },

    //4.单个删除
    handleDel: function (index, row) {
      //警告提示框
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //点击确定进入then方法中
        this.listLoading = true;//开启加载圈
        //发送异步请求,将对象的id传给后端
        this.$http.delete("/product/" + row.id).then(res => {
          if (res.data.success) {  //状态对象如果是true则删除成功进入if
            this.$message.success("删除成功!") //成功提示框
            //算出最后总页数
            var totalPage = Math.ceil(this.totals / this.pageSize);
            //如果当前页是总页数就是最后一页,并且个数模页数可以整除那就是每页最后一条,并且这不是第一页
            if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
              //满足条件就返回到删除页的前一页
              this.currentPage = this.currentPage - 1;
            }
            this.getProduct();//删除完后调用列表数据展示
            this.listLoading = false;//关闭加载圈
          } else {
            //如果状态对象为false则失败,弹框提醒用户
            this.$message.error("网络繁忙~~请稍后再试..")
          }
        }).catch(() => {  //catch则是有异常 弹窗提醒
          this.$message.error("网络繁忙~~请稍后再试..")
        });
      }).catch(() => {
        //提示框点击取消则弹窗提醒
        this.$message.error("请重新操作..")
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/product", ids).then(res => {
          if (res.data.success) {
            this.$message.success("删除成功")
            this.currentPage = 1;
            this.getProduct();
          } else {
            this.$message.error("网络繁忙...请稍后再试")
          }
        }).catch(res => {
          this.$message.error("网络繁忙...请稍后再试")
        })
      }).catch(() => {

      });
    },

    //7.点击添加弹出对话框
    handleAdd: function () {
      this.title = "添加";  //动态修改标题
      this.saveForm = {   //每次点击将form表单中数据清空
        id: null,
        name: '',
        costprice: null,
        saleprice: null,
        resources: '',
        salecount:null,
        state: null,
        offsaletime: '',
        onsaletime: '',
        createtime: '',
        productDetail: {  //与后端实体类一致
          intro: '',
          orderNotice: ''
        },
      };
      this.saveFormVisible = true;  //显示添加对话框
      this.getProduct();
      this.fileList = [];
    },

    //8.点击修改按钮弹出对话框
    handleSave: function (index, row) {
      this.$forceUpdate()
      //动态修改标题
      this.title = "修改";
      //回显数据
      //克隆对象防止列表中的数据也发生改变
      this.saveForm = Object.assign({}, row);//按照属性同名原则进行赋值
      //显示对话框
      this.saveFormVisible = true;
      this.getProduct();
      this.fileList = [];
      if (this.saveForm.resources) {
        let arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          this.fileList.push({"url": "http://123.207.27.208" + arr[i]});
        }
      }
    },


    //9.添加或者修改对话框单击事件处理
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => { //valid表单验证 满足条件则true
        if (valid) {
          //必填项都填了则弹窗确认提交框
          this.$confirm('确认提交吗？', '提示',
              {distinguishCancelAndClose: true}).then(() => {
            this.saveLoading = true;
            //NProgress.start(); 对象克隆,防止model改变原数据
            let para = Object.assign({}, this.saveForm);

            if (para.typeId == null || para.typeId.length == 0) {
              para.typeId = null;
            } else if (para.typeId.length != null) {
              //有值就将父ID给parentId
              para.typeId = para.typeId[para.typeId.length - 1]
            }
            //发送请求将克隆对象传入给后端
            this.$http.put("/product", para).then(res => {
              this.saveLoading = false; //关闭提交的加载框
              this.saveFormVisible = false; //关闭对话框
              if (res.data.success) {  //状态对象 操作成功则进入if
                this.$message.success("操作成功!");//弹窗提醒
                this.getProduct();//添加完成后关闭加载框、对话框并展示列表数据
              } else {
                this.$message.error("系统繁忙,请稍后再试！")//状态对象false 弹窗提醒
              }
            }).catch(res => {
              //代码错误,弹框提醒
              this.$message.error("系统繁忙,请稍后再试！")
            })
          });
        }
      })
    },


    onsale() {
      if (!this.sels || this.sels.length < 1) {
        this.$message.warning("请选中才上传哦!");
        return;
      }
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/product/onsale", ids).then(res => {
          if (res.data.success) {
            this.$message.success("上架成功!!!")
            this.getProduct();
          } else {
            this.$message.error("系统异常,请稍后再试..[500]")
          }
        }).catch(res => {
          this.$message.error("系统异常,请稍后再试...[404,400,405]")
        })
      }).catch(() => {
      });
    },

    offsale(){
      if (!this.sels || this.sels.length < 1) {
        this.$message.warning("请选中下架哦!");
        return;
      }
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/product/offsale", ids).then(res => {
          if (res.data.success) {
            this.$message.success("下架成功!!!");
            this.getProduct();
          } else {
            this.$message.error("系统异常,请稍后再试..[500]")
          }
        }).catch(res => {
          this.$message.error("系统异常,请稍后再试...[404,400,405]")
        })
      }).catch(() => {
      });
    }
  },

  mounted() {
    this.getProduct();
    this.spilit()
  }
}

</script>

<style scoped></style>